import {get as getCache, save, LOCAL} from '$ui/utils/storage'
import buildConfig from '../../my.config.js'

const LOCAL_CACHE_KEY = '__MY_M_SKIN__'
const publicPath = process.env.NODE_ENV === 'production' ? buildConfig.publicPath : ''

function createCacheKey(app) {
  return app ? `__MY_M_SKIN_${app}__` : LOCAL_CACHE_KEY
}

function setBodyClass(theme) {
  const classList = document.body.classList
  classList.forEach((name) => {
    if (name.includes(LOCAL_CACHE_KEY)) {
      classList.remove(name)
    }
  })

  classList.add(`${LOCAL_CACHE_KEY}${theme}`)
}


function setTheme(key, app, container) {
  const domId = `my-m-skin-link-${app || 'master'}`
  // const mapName = app ? `__MY_THEMES_${app}__`
  const theme = `${publicPath}/assets/vant-themes/${key}/index.css`
  let linkEl = document.getElementById(domId)
  if (linkEl) {
    linkEl.parentNode.removeChild(linkEl)
  }
  if (theme) {
    linkEl = document.createElement('link')
    linkEl.id = domId
    linkEl.rel = 'stylesheet'
    linkEl.href = theme
    const parent = container || document.getElementById('my-master-app') || document.body
    if (parent) {
      parent.appendChild(linkEl)
    }
  }
}


/**
 * 更换主题
 * @param {string} theme 主题名
 * @param {string} app 子应用名称
 * @param {boolean} isMaster 主题名称跟随主应用
 * @param {HTMLDivElement} container
 */

export function change({theme, app, isMaster, container}) {
  save(createCacheKey(isMaster ? null : app), theme, LOCAL)
  setTheme(theme, app, container)
  setBodyClass(theme)
}

export function get(app = '', isMaster) {
  return getCache(createCacheKey(isMaster ? null : app), LOCAL) || null
}

export default function (app, isMaster) {
  return {
    inject: {
      appProps: {default: null},
      masterApp: {default: null}
    },
    data() {
      return {
        skin: get(app, isMaster) || 'default'
      }
    },
    watch: {
      skin: {
        immediate: true,
        handler(val) {
          this.changeTheme(val)
        }
      }
    },
    methods: {
      changeTheme(name) {
        change({
          theme: name,
          app,
          isMaster,
          container: this.appProps ? this.appProps.container : null
        })
        const state = {skin: name}
        if (this.appProps?.setGlobalState) {
          this.appProps.setGlobalState(state)
        }
        if (this.masterApp) {
          this.masterApp.setState(state)
        }
      },
      storageChangeHandler(evt) {
        if (!evt.key.startsWith(LOCAL_CACHE_KEY)) return
        this.skin = evt.newValue
      },
      handleStateChange(state) {
        this.skin = state.skin || 'default'
      }
    },
    created() {
      window.addEventListener('storage', this.storageChangeHandler)
      if (this.masterApp) {
        this.masterApp.onStateChange(this.handleStateChange)
      }
      if (this.appProps?.onGlobalStateChange) {
        this.appProps.onGlobalStateChange(this.handleStateChange)
      }
    },
    beforeDestroy() {
      window.removeEventListener('storage', this.storageChangeHandler)
    }
  }

}